use std::{collections::HashMap, sync::Mutex, rc::Rc, cell::RefCell};

use once_cell::sync::Lazy;

use crate::rtda::Frame;



pub type NativeMethod = fn(Rc<RefCell<Frame>>);

// 具体方法实现map
pub static REGISTRY: Lazy<Mutex<HashMap<String, NativeMethod>>> = Lazy::new(|| Mutex::new(HashMap::new()));

// 注册本地方法
pub fn register(class_name: &str, method_name: &str, method_descriptor: &str, method: NativeMethod) {
    let key = class_name.to_string() + "-" + method_name + "-" + method_descriptor;
    REGISTRY.lock().unwrap().insert(key, method);
}

// 根据类名、方法名和方法描述符查找本地方法实现
pub fn find_native_method(class_name: &str, method_name: &str, method_descriptor: &str) -> Option<NativeMethod> {
    let key = class_name.to_string() + "-" + method_name + "-" + method_descriptor;
    // assert!(REGISTRY.lock().unwrap().contains_key(&key), "not constant key: {}", key);
    if let Some(method) = REGISTRY.lock().unwrap().get(&key) {
        return Some(method.clone());
    }
    if method_descriptor == "()V" && (method_name == "registerNatives" || method_name == "initIDs") {
        // enpty_native_method do nothing
        return Some(|_| ());
    }
    None
}